<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import type { TestHistoryItem, TestHistoryResponse } from '@/types/healthTest'
import { getTestHistory } from '@/services/healthTest'

// 测试类型映射
const testTypeMap = {
  'HT1': {
    name: '抑郁测试',
    icon: 'https://myfirst-bucket01.oss-cn-guangzhou.aliyuncs.com/banner.jpg'
  },
  'HT2': {
    name: 'FPA性格色彩测试',
    icon: 'https://myfirst-bucket01.oss-cn-guangzhou.aliyuncs.com/R-C.png'
  },
  'HT3': {
    name: '经典情商(EQ)测试',
    icon: 'https://myfirst-bucket01.oss-cn-guangzhou.aliyuncs.com/veer-311702881.jpg'
  }
}

// 页面数据
const allHistoryList = ref<TestHistoryItem[]>([]) // 存储所有数据
const total = ref(0)
const current = ref(1)
const size = ref(10)
const loading = ref(false)
const activeType = ref('all') // 当前选中的测试类型

// 根据类型筛选的历史记录
const filteredHistoryList = computed(() => {
  const list = activeType.value === 'all' 
    ? allHistoryList.value 
    : allHistoryList.value.filter(item => item.htId === activeType.value)
  
  // 计算当前页的数据
  const start = (current.value - 1) * size.value
  const end = start + size.value
  return list.slice(start, end)
})

// 计算筛选后的总数
const filteredTotal = computed(() => {
  return activeType.value === 'all'
    ? allHistoryList.value.length
    : allHistoryList.value.filter(item => item.htId === activeType.value).length
})

// 计算总页数
const totalPages = computed(() => Math.ceil(filteredTotal.value / size.value))

// 获取测试历史记录
const loadTestHistory = async () => {
  try {
    loading.value = true
    const res = await getTestHistory(1, 999) // 获取所有数据
    allHistoryList.value = res.data.records
    
    // 如果当前页码超出范围，重置为最后一页
    if (current.value > totalPages.value) {
      current.value = Math.max(1, totalPages.value)
    }
  } catch (error) {
    uni.showToast({
      title: '获取历史记录失败',
      icon: 'error'
    })
  } finally {
    loading.value = false
  }
}

// 查看测试结果详情
const viewTestDetail = (item: TestHistoryItem) => {
  uni.navigateTo({
    url: `/pages/health/componets/ResultShow?testResultTitle=${item.htResTitle}&testResult=${item.htResContent}`
  })
}

// 切换测试类型
const switchType = (type: string) => {
  if (type === activeType.value) return
  activeType.value = type
  current.value = 1 // 切换类型时重置为第一页
}

// 页码改变
const handlePageChange = (e: { type: string, current: number }) => {
  if (e.current === current.value) return
  current.value = e.current
  // 滚动到页面顶部
  uni.pageScrollTo({
    scrollTop: 0,
    duration: 300
  })
}

onMounted(() => {
  loadTestHistory()
})
</script>

<template>
  <view class="history-container">
    <view class="history-header">
      <text class="header-title">测试历史记录</text>
    </view>

    <!-- 测试类型选择 -->
    <scroll-view scroll-x class="type-scroll">
      <view class="type-list">
        <view 
          class="type-item" 
          :class="{ active: activeType === 'all' }"
          @tap="switchType('all')"
        >
          全部 ({{ allHistoryList.length }})
        </view>
        <view 
          v-for="(type, id) in testTypeMap" 
          :key="id"
          class="type-item"
          :class="{ active: activeType === id }"
          @tap="switchType(id)"
        >
          {{ type.name }} ({{ allHistoryList.filter(item => item.htId === id).length }})
        </view>
      </view>
    </scroll-view>
    
    <view v-if="loading" class="loading">
      <uni-load-more status="loading" />
    </view>
    
    <view v-else-if="filteredHistoryList.length === 0" class="empty">
      <text>暂无测试记录</text>
    </view>
    
    <view v-else class="history-list">
      <view 
        v-for="item in filteredHistoryList" 
        :key="item.prId" 
        class="history-item"
        @tap="viewTestDetail(item)"
      >
        <view class="item-header">
          <view class="test-info">
            <image class="test-icon" :src="testTypeMap[item.htId]?.icon" mode="aspectFill" />
            <view class="test-detail">
              <text class="test-type">{{ testTypeMap[item.htId]?.name }}</text>
              <text class="test-title">{{ item.htResTitle }}</text>
            </view>
          </view>
          <text class="test-time">{{ item.htTime }}</text>
        </view>
        <view class="item-content">
          <text class="result-preview">{{ item.htResContent.substring(0, 50) }}...</text>
        </view>
        <view class="item-footer">
          <text class="view-detail">查看详情 ></text>
        </view>
      </view>
      
      <!-- 分页组件 -->
      <view v-if="filteredTotal > 0" class="pagination-box">
        <uni-pagination
          :total="filteredTotal"
          :pageSize="size"
          :current="current"
          :totalText="true"
          @change="handlePageChange"
          showIcon
        />
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.history-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
  
  .history-header {
    padding: 30rpx 0;
    text-align: center;
    
    .header-title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .type-scroll {
    background-color: #fff;
    padding: 20rpx 0;
    margin-bottom: 20rpx;
    white-space: nowrap;

    .type-list {
      display: inline-flex;
      padding: 0 20rpx;

      .type-item {
        padding: 10rpx 30rpx;
        margin-right: 20rpx;
        border-radius: 30rpx;
        font-size: 28rpx;
        color: #666;
        background-color: #f5f5f5;
        transition: all 0.3s;

        &.active {
          color: #fff;
          background-color: #4a90e2;
        }

        &:last-child {
          margin-right: 0;
        }
      }
    }
  }
  
  .loading,
  .empty {
    padding: 40rpx 0;
    text-align: center;
    color: #999;
  }
  
  .history-list {
    .history-item {
      margin-bottom: 20rpx;
      padding: 30rpx;
      background-color: #fff;
      border-radius: 12rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
      
      .item-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 20rpx;
        
        .test-info {
          display: flex;
          align-items: center;
          flex: 1;
          margin-right: 20rpx;

          .test-icon {
            width: 80rpx;
            height: 80rpx;
            border-radius: 10rpx;
            margin-right: 20rpx;
          }

          .test-detail {
            display: flex;
            flex-direction: column;

            .test-type {
              font-size: 28rpx;
              color: #666;
              margin-bottom: 10rpx;
            }

            .test-title {
              font-size: 32rpx;
              font-weight: bold;
              color: #333;
            }
          }
        }
        
        .test-time {
          font-size: 24rpx;
          color: #999;
        }
      }
      
      .item-content {
        margin-bottom: 20rpx;
        
        .result-preview {
          font-size: 28rpx;
          color: #666;
          line-height: 1.5;
        }
      }
      
      .item-footer {
        text-align: right;
        
        .view-detail {
          font-size: 26rpx;
          color: #4a90e2;
        }
      }
    }
    
    .pagination-box {
      margin: 30rpx 0;
      display: flex;
      justify-content: center;
    }
  }
}
</style> 